import { IMG_URL, currentEnv } from "../config";
import { marked } from "marked";
import dompurify from 'dompurify';
const DOMPurify = dompurify(window)
import type { Article } from "@/api/type";
import type { InjectionKey } from "vue";
const STORAGE_PREFIX = "ZYL_FORMULA_";
import axios from "axios";
import showdown from 'showdown';
import showdownKatex from 'showdown-katex';

export const loadFromLocal = (key: string) => {
	return localStorage.getItem(`${STORAGE_PREFIX}${key}`);
};

export const saveToLocal = (key: string, value: string) => {
	return localStorage.setItem(`${STORAGE_PREFIX}${key}`, value);
};

export const removeLocal = (key: string) => {
	return localStorage.removeItem(`${STORAGE_PREFIX}${key}`);
};

export function getDateCN(value?: number| string) {
	const innerVal = value || Date.now();
	const now = new Date(innerVal);
	const y = now.getFullYear();
	return (
		`${y}年`
	);
}


export function getDate(value?: number| string, sep = "-") {
	const innerVal = value || Date.now();
	const now = new Date(innerVal);
	const y = now.getFullYear();
	const m = now.getMonth() + 1;
	const d = now.getDate();
	return (
		`${y +
		sep +
		(m < 10 ? `0${m}` : m) +
		sep +
		(d < 10 ? `0${d}` : d)}`
	);
}

export const getDateStr = (value?: number| string, sep = "-") => {
	const innerVal = value || Date.now();
	const now = new Date(innerVal);
	const y = now.getFullYear();
	const m = now.getMonth() + 1;
	const d = now.getDate();
	return (
		`${y +
		sep +
		(m < 10 ? `0${m}` : m) +
		sep +
		(d < 10 ? `0${d}` : d)} ${now.toTimeString().substr(0, 8)}`
	);
};


//获取更符合小程序规范的html
export const betterHtml = (richHtml: string) => {
	return DOMPurify.sanitize(richHtml)
};
const customRender = new marked.Renderer()

customRender.code = function(code: string, language: string| undefined) {
console.log('code', code)
return code.text
}
export const transformMsg =(msgInfo = "")=> {
	console.warn('msgInfo', msgInfo)
	const converter = new showdown.Converter({
	  // 详细配置见：https://github.com/showdownjs/showdown#valid-options
	  tables: true,  // 支持table语法
	  strikethrough: true,  // 将~~strikethrough~~ 识别为 <del>strikethrough</del>
	  underline: true,  // __test__中的下划线不识别为<em> 和 <strong>
	  extensions: [
		showdownKatex({
		  // 使用方式见：https://obedm503.github.io/showdown-katex
		  // 详细配置见：https://katex.org/docs/options.html
		  throwOnError: false,  // 公式有错时，是否抛出错误
		  displayMode: true,  // 如果为false，公式以inline方式渲染
		  delimiters: [
			{ left: "$$", right: "$$", display: true,  },
			{ left: "$", right: "$", display: false,},
			// { left: "[", right: "]", display: false },
			// { left: "~", right: "~", display: false, asciimath: true },
		  ],
		}),
	  ],
	});
	return converter.makeHtml(msgInfo);
  }

export const imgTagRegex =  (richText: string) =>{
	const imgTagRegex = /https?:\/\/[^\s/$.?#].[^\s]*\.(png|jpg)/g

  richText = richText.replace(imgTagRegex, (match: any, href:any, text:any) => {
    console.log('imgTagRegex', match, href, text)
		  return `<img style="width: 100%;" src="${match}" alt="${text}" />`;
	});
  return  richText
}

//对 uni.navigateTo 的二次封装
export const navigateTo = async (args: any) => {
	console.log(args);
	// if (store.state.token && !store.state.userId) {
	//   await store.dispatch('actionUserInfo')
	// }
	// uni.navigateTo(object)
};

//对 uni.navigateBack 的二次封装
export const navigateBack = async (args: any) => {
	console.log(args);
	// if (store.state.token && !store.state.userId) {
	//   await store.dispatch('actionUserInfo')
	// }
	// uni.navigateTo(object)
};

export function getPosterURL(path: string, id: string) {
	//线上环境
	// return `http://192.168.30.2:3000/api/image?path=${path}&id=${id}`
	// http://120.78.141.193:3000/
	//本地环境
	return `${IMG_URL}/api/image?path=${path}&id=${id}&env=${currentEnv}`;
}

function addIndex(o: any, index: number) {
	return {
		...o,
		index: index + 1,
	};
}


export interface ObjectWithId extends Article {
	id: string;
}
export interface withIdx extends ObjectWithId {
	indexs: string[];
}
/**
 * 合并引用源 - 数据
 * @param {*} list
 * @returns
 */
export function transformRelateArticle(list?: Array<ObjectWithId>) {
	const ret = list?.map(addIndex).reduce(
		(map, now) => {
			if (!map[now.id]) {
				const newOne: withIdx = {
					...now,
					indexs: [now?.index],
				};
				map.result.push(newOne);
				map[now.id] = newOne;
				return map;
			}

			map[now.id].indexs.push(now.index);
			return map;
		},
		{
			result: [],
		},
	).result as withIdx[];

	return ret;
}

//scroll
export const scroll = Symbol('scroll') as InjectionKey<() => void>

export function getFutureDate(daysToAdd: number = 365) {
  // Get the current time
  const now = new Date();
  
  // Add the specified number of days to the current time
  const futureDate = new Date(now.getTime() + daysToAdd * 24 * 60 * 60 * 1000);
  
  // Format to YYYY-MM-DD HH:mm:ss
  const year = futureDate.getFullYear();
  const month = String(futureDate.getMonth() + 1).padStart(2, '0'); // Months are zero-based
  const day = String(futureDate.getDate()).padStart(2, '0');
  const hours = String(futureDate.getHours()).padStart(2, '0');
  const minutes = String(futureDate.getMinutes()).padStart(2, '0');
  const seconds = String(futureDate.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

export const getImgUrl = (name:string) =>{
	return new URL(`../${name}`, import.meta.url).href
}

export function isMobile() {
  const flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
  return flag
}

export function isJSON(str: any) {
  if (typeof str === 'string') {
    try {
      JSON.parse(str)
      return true
    } catch (e) {
      return false
    }
  } else {
    return false
  }
}

export function getMarkeDom(value:string) {
	return new Promise((resolve, reject) => {
		axios.get(value).then(res =>{
			console.warn('22',res.data)
			resolve(transformMsg(res.data))
		})
	    
	})
}

export function getBlob(value:any) {
	return new Promise((resolve, reject) => {
		axios.get(value, { responseType: 'blob' }).then(res =>{
			resolve(res.data)})})
}

/** 拆分数组 */
export const chunkArray = (arr: Array<any>, size: number) =>
  Array.from({ length: Math.ceil(arr.length / size) }, (_, i) =>
    arr.slice(i * size, i * size + size)
  )

  // 自定义指令 只允许输入整数
export const vIntegerOnly = {
	mounted(el, binding, vnode) {
	  el.addEventListener('input', () => {
		let value = el.value;
		value = value.replace(/[^0-9]/g, ''); // 移除非数字字符
		if (value !== '') {
		  el.value = value;
		} else {
		  el.value = binding.oldValue || '';
		}
	  });
	},
	updated(el, binding, vnode) {
	  let value = el.value;
	  value = value.replace(/[^0-9]/g, ''); // 移除非数字字符
	  if (value !== '') {
		el.value = value;
	  } else {
		el.value = binding.oldValue || '';
	  }
	}
  };